﻿<%@ WebHandler Language="C#" Class="Training.Web.AjaxHandler.Administration.Catalog.PelatihanHandler" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;

using Training.Library.DataAccess.Administration;
using Training.Library.DomainObject.Administration;
using Training.Library.DataAccess.Administration.Catalog;
using Training.Library.DomainObject.Administration.Catalog;
using Training.Library.DomainObject.Transaction;
using System.Web.SessionState;

using Training.Library.Enum;
using Training.Web.Support;
using Newtonsoft.Json.Linq;
namespace Training.Web.AjaxHandler.Administration.Catalog
{

    public class PelatihanHandler : Training.Web.BaseHandler,IRequiresSessionState
    {
        private  PelatihanRepo PelatihanDal = new PelatihanRepo(ConfigurationManager.ConnectionStrings["TrainingConn"].ConnectionString);
        private recLogRepo logDal = new recLogRepo(ConfigurationManager.ConnectionStrings["TrainingConn"].ConnectionString);
        private string MethodName = string.Empty;
        private CabangRepo CabangDal = new CabangRepo(ConfigurationManager.ConnectionStrings["TrainingConn"].ConnectionString);

        public override void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);
            MethodName = context.Request.Params["method"];
            context.Response.Clear();
            context.Response.Buffer = true;

            System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream);
            string jsonString = string.Empty;
            jsonString = context.Server.UrlDecode(sr.ReadToEnd());
            JObject jObj = string.IsNullOrEmpty(jsonString) ? null : JObject.Parse(jsonString);

            sr.Close();
            sr.Dispose();

            switch (MethodName.ToLower())
            {
                case ("insert"):
                    context.Response.Write(Insert(context, jObj));
                    break;
                case ("update"):
                    context.Response.Write(Update(context, jObj));
                    break;
                case ("delete"):
                    context.Response.Write(Delete(context, jObj));
                    break;
                case ("getdata"):
                    context.Response.Write(GetData(context));
                    break;
                case ("getdatabypembicara"):
                    context.Response.Write(GetDataByPembicara(context));
                    break;
                case ("getdatabypeserta"):
                    context.Response.Write(GetDataByPeserta(context));
                    break;

                default:
                    // do nothing
                    break;
            }

            context.Response.Flush();
            context.Response.End();
        }

        public override bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private string Insert(HttpContext context, JObject jo)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                DateTime Tgl = Helper.FormatDate(jo["Tgl"].ToString(), Helper.Culture.Indonesian);
                DateTime TglAkhir = Helper.FormatDate(jo["TglAkhir"].ToString(), Helper.Culture.Indonesian);
                
                Pelatihan obj = new Pelatihan();
                obj.NamaPelatihan = (string)jo["Nama"];
                obj.PembicaraID = (int)jo["Pembicara"];
                obj.TempatPelatihan = (string)jo["Tempat"];
                obj.TglPelatihan = Tgl;
                obj.TglAkhirPelatihan = TglAkhir;
                obj.CreatedDate = DateTime.Now;
                obj.CreatedBy = base.UserLoggedIn;
                if (base.CabangID != null)
                    obj.CabangID = base.CabangID;

                List<PelatihanDetail> listPelatihanDetail = new List<PelatihanDetail>();
                if (context.Session["PelatihanDetail"] != null)
                {
                     listPelatihanDetail = context.Session["PelatihanDetail"] as List<PelatihanDetail>;
                }

                PelatihanDal.Save(obj,listPelatihanDetail);

                helper.Message = "Data berhasil di simpan !";
                helper.IsSuccess = true;

            }
            catch (Exception ex)
            {

                helper.Message = ex.Message;
                helper.IsSuccess = false;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Insert";
                log.LogMessage = helper.Message;
                log.LogSource = "Pelatihanhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);

                context.Session.Remove("PelatihanDetail");

            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string Update(HttpContext context, JObject jo)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                DateTime Tgl = Helper.FormatDate(jo["Tgl"].ToString(), Helper.Culture.Indonesian);
                DateTime TglAkhir = Helper.FormatDate(jo["TglAkhir"].ToString(), Helper.Culture.Indonesian);
                Pelatihan obj = new Pelatihan();
                obj.PelatihanID = (int)jo["PelatihanID"];
                obj.NamaPelatihan = (string)jo["Nama"];
                obj.PembicaraID = (int)jo["Pembicara"];
                obj.TempatPelatihan = (string)jo["Tempat"];
                obj.TglPelatihan = Tgl;
                obj.TglAkhirPelatihan = TglAkhir;
                obj.UpdatedDate = DateTime.Now;
                obj.UpdatedBy = base.UserLoggedIn;
                if (base.CabangID != null)
                    obj.CabangID = base.CabangID;

                List<PelatihanDetail> listPelatihanDetail = new List<PelatihanDetail>();
                if (context.Session["PelatihanDetail"] != null)
                {
                    listPelatihanDetail = context.Session["PelatihanDetail"] as List<PelatihanDetail>;
                }

                PelatihanDal.Update(obj,listPelatihanDetail);
                helper.Message = "Data berhasil di ubah !";
                helper.IsSuccess = true;
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Update";
                log.LogMessage = helper.Message;
                log.LogSource = "Pelatihanhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);

                context.Session.Remove("PelatihanDetail");
            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string Delete(HttpContext context, JObject jo)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                var strId = (string)jo["ID"];

                string[] ids = strId.Split(',');
                foreach (string id in ids)
                {
                    int intID = Convert.ToInt32(id);
                    PelatihanDal.Delete(intID);
                }

                helper.IsSuccess = true;
                helper.Message = "Data berhasil di hapus !";
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Delete";
                log.LogMessage = helper.Message;
                log.LogSource = "Pelatihanhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);

            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string GetData(HttpContext context)
        {
            string parameters = Helper.JqGridFilterToSQLParams(context);

            if (base.CabangID != null)
            {
                Cabang objCabang = CabangDal.GetById(base.CabangID);
                if (objCabang != null)
                {
                    if (!objCabang.NamaCabang.Trim().ToLower().Contains("kantor pusat"))
                        parameters = parameters == string.Empty ? " WHERE Pelatihan.CabangID=" + base.CabangID : parameters + " AND Pelatihan.CabangID=" + base.CabangID;
                }
            }

            int page = 1;
            int.TryParse(context.Request.QueryString["page"] ?? "1", out page);

            int pageSize = 10;
            int.TryParse(context.Request.QueryString["rows"] ?? "10", out pageSize);

            string sidx = ((context.Request.QueryString["sidx"]) == null ? Pelatihan.Fields.PelatihanID : context.Request.QueryString["sidx"].ToString());

            string sord = ((context.Request.QueryString["sord"]) == null ? "ASC" : context.Request.QueryString["sord"].ToString());

            int totalCount = 0;
            int totalPages = 0;
            List<Pelatihan> pagedList = null;

            try
            {
                totalCount = Convert.ToInt32(PelatihanDal.SelectScalar(SQL.Function.Aggregate.Count, Pelatihan.Fields.PelatihanID, parameters));

                decimal dc = decimal.Ceiling(Convert.ToDecimal(totalCount) / Convert.ToDecimal(pageSize));
                totalPages = Convert.ToInt32(dc);

                pagedList = PelatihanDal.GetList(pageSize, page, sidx, sord, parameters);
            }
            catch (Exception ex)
            {
                recLog log = new recLog();
                log.LogEvent = "GetData";
                log.LogMessage = ex.Message;
                log.LogSource = "Pelatihanhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
                log.Dispose();
            }
            finally
            {

            }

            // send params into jqGrid's format
            var gridData = new
            {
                page = page,
                total = totalPages,
                records = totalCount,
                rows = pagedList,
            };

            return Newtonsoft.Json.JsonConvert.SerializeObject(gridData);

        }

        private string GetDataByPembicara(HttpContext context)
        {
            string parameters = Helper.JqGridFilterToSQLParams(context);

            if (context.Request.Params["pembicaraID"] != null)
                parameters = parameters == string.Empty ? " WHERE Pelatihan.PembicaraID=" + context.Request.Params["pembicaraID"].ToString().Trim() : parameters + " AND Pelatihan.PembicaraID=" + context.Request.Params["pembicaraID"].ToString().Trim();
          

            int page = 1;
            int.TryParse(context.Request.QueryString["page"] ?? "1", out page);

            int pageSize = 10;
            int.TryParse(context.Request.QueryString["rows"] ?? "10", out pageSize);

            string sidx = ((context.Request.QueryString["sidx"]) == null ? Pelatihan.Fields.PelatihanID : context.Request.QueryString["sidx"].ToString());

            string sord = ((context.Request.QueryString["sord"]) == null ? "ASC" : context.Request.QueryString["sord"].ToString());

            int totalCount = 0;
            int totalPages = 0;
            List<Pelatihan> pagedList = null;

            try
            {
                totalCount = Convert.ToInt32(PelatihanDal.SelectScalar(SQL.Function.Aggregate.Count, Pelatihan.Fields.PelatihanID, parameters));

                decimal dc = decimal.Ceiling(Convert.ToDecimal(totalCount) / Convert.ToDecimal(pageSize));
                totalPages = Convert.ToInt32(dc);

                pagedList = PelatihanDal.GetList(pageSize, page, sidx, sord, parameters);
            }
            catch (Exception ex)
            {
                recLog log = new recLog();
                log.LogEvent = "GetData";
                log.LogMessage = ex.Message;
                log.LogSource = "Pelatihanhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
                log.Dispose();
            }
            finally
            {

            }

            // send params into jqGrid's format
            var gridData = new
            {
                page = page,
                total = totalPages,
                records = totalCount,
                rows = pagedList,
            };

            return Newtonsoft.Json.JsonConvert.SerializeObject(gridData);

        }

        private string GetDataByPeserta(HttpContext context)
        {
            string parameters = Helper.JqGridFilterToSQLParams(context);

            if (context.Request.Params["pesertaID"] != null)
                parameters = parameters == string.Empty ? " WHERE PelatihanDetail.PesertaID=" + context.Request.Params["pesertaID"].ToString().Trim() : parameters + " AND Pelatihan.PesertaID=" + context.Request.Params["pesertaID"].ToString().Trim();


            int page = 1;
            int.TryParse(context.Request.QueryString["page"] ?? "1", out page);

            int pageSize = 10;
            int.TryParse(context.Request.QueryString["rows"] ?? "10", out pageSize);

            string sidx = ((context.Request.QueryString["sidx"]) == null ? Pelatihan.Fields.PelatihanID : context.Request.QueryString["sidx"].ToString());

            string sord = ((context.Request.QueryString["sord"]) == null ? "ASC" : context.Request.QueryString["sord"].ToString());

            int totalCount = 0;
            int totalPages = 0;
            List<Pelatihan> pagedList = null;

            try
            {
                totalCount = Convert.ToInt32(PelatihanDal.SelectScalarByPeserta(SQL.Function.Aggregate.Count,"Pelatihan.PelatihanID", parameters));

                decimal dc = decimal.Ceiling(Convert.ToDecimal(totalCount) / Convert.ToDecimal(pageSize));
                totalPages = Convert.ToInt32(dc);

                pagedList = PelatihanDal.GetListByPeserta(pageSize, page, sidx, sord, parameters);
            }
            catch (Exception ex)
            {
                recLog log = new recLog();
                log.LogEvent = "GetData";
                log.LogMessage = ex.Message;
                log.LogSource = "Pelatihanhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
                log.Dispose();
            }
            finally
            {

            }

            // send params into jqGrid's format
            var gridData = new
            {
                page = page,
                total = totalPages,
                records = totalCount,
                rows = pagedList,
            };

            return Newtonsoft.Json.JsonConvert.SerializeObject(gridData);

        }

    }

}